package com.edu.base.rest.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.edu.base.ums.member.domain.ClsMember;
import com.edu.base.ums.umsMember.domain.UmsMember;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * token验证处理
 *
 * @author ruoyi
 */
@Component
public class AppTokenService
{
    // 令牌自定义标识
    @Value("${token.appheader}")
    private String appheader;

    // 令牌秘钥
    @Value("${token.secret}")
    private String secret;

    // 令牌有效期（默认30分钟）
    @Value("${token.expireTime}")
    private int expireTime;

    // 令牌有效期（默认30分钟）
    @Value("${token.appexpireTime}")
    private int appExpireTime;

    protected static final long MILLIS_SECOND = 1000;

    protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;

    private static final Long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;

    @Autowired
    private RedisCache redisCache;
    
    //设置过期时间
    private static final long EXPIRE_DATE= 30*60*100000;
    //token秘钥
    private static final String TOKEN_SECRET = "ZCEQIUBFKSJBFJH2020BQWE";

    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public UmsMember getAppUmsMember(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            Claims claims = parseToken(token);
            // 解析对应的权限以及用户信息
            String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
            String userKey = getTokenKey(uuid);
            UmsMember umsMember = redisCache.getCacheObject(userKey);
            return umsMember;
        }
        return null;
    }

    public ClsMember getAppMember(HttpServletRequest request)
    {
        // 获取请求携带的令牌
        String token = getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
                Claims claims = parseToken(token);
                // 解析对应的权限以及用户信息
                String uuid = (String) claims.get(Constants.APP_LOGIN_USER_KEY);
                String userKey = getTokenKey(uuid);
                ClsMember clsMember = redisCache.getCacheObject(userKey);
                return clsMember;
        }
        return null;
    }

    /**
     * 设置用户身份信息
     */
    public void setAppLoginUser(UmsMember umsMember)
    {
        if (StringUtils.isNotNull(umsMember))
        {
            refreshToken(umsMember);
        }
    }

    public void setAppLoginUser(ClsMember clsMember)
    {
        if (StringUtils.isNotNull(clsMember))
        {
            refreshToken(clsMember);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token)
    {
        if (StringUtils.isNotEmpty(token))
        {
            String userKey = getTokenKey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 创建令牌
     *
     * @return 令牌
     */
    public String createToken(ClsMember clsMember)
    {
        //String token = IdUtils.fastUUID();
        //clsMember.setToken(token);
        //setUserAgent(clsMember);
        refreshToken(clsMember);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.APP_LOGIN_USER_KEY, clsMember.getId());
        return createToken(claims);
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @return 令牌
     */
    public void verifyToken(UmsMember umsMember)
    {
        long expireTime = umsMember.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(umsMember);
        }
    }

    public void verifyToken(ClsMember clsMember)
    {
        long expireTime = clsMember.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if (expireTime - currentTime <= MILLIS_MINUTE_TEN)
        {
            refreshToken(clsMember);
        }
    }

    /**
     * 刷新令牌有效期
     *
     */
    public void refreshToken(UmsMember umsMember)
    {
    	umsMember.setLoginTime(new Date(System.currentTimeMillis()));
    	umsMember.setExpireTime(umsMember.getLoginTime().getTime() + appExpireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(umsMember.getToken());
        redisCache.setCacheObject(userKey, umsMember, appExpireTime, TimeUnit.MINUTES);
    }

    public void refreshToken(ClsMember clsMember)
    {
        clsMember.setLoginTime(new Date(System.currentTimeMillis()));
        clsMember.setExpireTime(clsMember.getLoginTime().getTime() + appExpireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(clsMember.getId());
        redisCache.setCacheObject(userKey, clsMember, appExpireTime, TimeUnit.MINUTES);
    }

    /**
     * 设置用户代理信息
     *
     */
    public void setUserAgent(ClsMember clsMember)
    {
        UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
        String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
        //clsMember.setIpaddr(ip);
        //clsMember.setLoginLocation(AddressUtils.getRealAddressByIP(ip));
        //clsMember.setBrowser(userAgent.getBrowser().getName());
        //clsMember.setOs(userAgent.getOperatingSystem().getName());
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private String createToken(Map<String, Object> claims)
    {
        String token = Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, secret).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims parseToken(String token)
    {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token)
    {
        Claims claims = parseToken(token);
        return claims.getSubject();
    }

    /**
     * 获取请求token
     *
     * @param request
     * @return token
     */
    private String getToken(HttpServletRequest request)
    {
        String token = request.getHeader(appheader);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX))
        {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        return token;
    }

    private String getTokenKey(String uuid)
    {
        return Constants.APP_LOGIN_TOKEN_KEY + uuid;
    }
    
    /********************************************/
    //实现签名方法
    public  String token (String username,String password){ 
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis()+appExpireTime * MILLIS_MINUTE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            //设置头部信息
            Map<String,Object> header = new HashMap<>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("username",username)
                    .withClaim("password",password).withExpiresAt(date)
                    .sign(algorithm);
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
        return token;
    }
    
    public  boolean verify(String token){
        /**
         * @desc   验证token，通过返回true
         * @create 2019/1/18/018 9:39
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return  false;
        }
    }
    
    /**
     * 刷新令牌有效期
     *
     * @param clsMember 登录信息
     */
    public void refreshAppToken(ClsMember clsMember)
    {
    	clsMember.setLoginTime(new Date(System.currentTimeMillis()));
    	clsMember.setExpireTime(clsMember.getLoginTime().getTime() + appExpireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenKey(clsMember.getId());
        redisCache.setCacheObject(userKey, clsMember, appExpireTime, TimeUnit.MINUTES);
    }

    public boolean deleteToken(String memberId){
        String userKey = getTokenKey(memberId);
        return redisCache.deleteObject(userKey);
    }
}
